#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
THN DATA ABSTRACTION LAYER version 1

Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

This library is dual-licensed.
  + For commercial software, please obtain a commercial license from THN Solutions LLC.

  + For free software, this library is licensed under GPL version 3. A summary of GPLv3 is
    listed below. You should also find a copy of GPLv3 as file License_GPLv3.txt included
	with the source-code files.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 3 as published by
    the Free Software Foundation  of the License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#endregion

#region Using directives
using System;
using System.Collections;
using Thn.Data.Exceptions;
#endregion

namespace Thn.Data.Query
{
    /// <summary>
    /// Base class for a structured query language expression
    /// </summary>
    public abstract class QueryBase
    {
        /// <summary>
        /// The query which is one level higher than me
        /// </summary>
        protected QueryBase mParentQuery = null;

        #region Parent
        private Transaction mParentTransaction;
        /// <summary>
        /// Gets/Sets the transaction that own this query command
        /// </summary>
        public Transaction ParentTransaction
        {
            get { return mParentTransaction; }
            set { mParentTransaction = value; }
        }
        #endregion

        #region Processor
        private IQueryProcessor mProcessor;
        /// <summary>
        /// Gets/Sets the owner that will execute this command
        /// </summary>
        public IQueryProcessor Processor
        {
            get { return mProcessor; }
            set { mProcessor = value; }
        }
        #endregion
		
        #region Append Query
        /// <summary>
        /// Add a query command to parent transaction's command lists. Lazy initialize list if needed.
        /// </summary>
        protected void AppendQueryToParent(QueryBase value)
        {            
            if (mParentTransaction.Commands == null) mParentTransaction.Commands = new QueryCollection();

            mParentTransaction.Commands.Add(value);
        }

        /// <summary>
        /// Append a query to this query's transaction (if this is a TransactionQuery) or this query's parent transaction
        /// </summary>
        protected void AppendQueryToTransaction(QueryBase value)
        {
            if (this is TransactionQuery)
            {
                value.mParentQuery = this;
                ((TransactionQuery)this).Transaction.Commands.Add(value);
            }
            else
            {
                value.mParentQuery = this.mParentQuery;
                mParentTransaction.Commands.Add(this);
            }
        }
        #endregion

        #region Insert
        /// <summary>
        /// Insert object(s) to database
        /// </summary>
        public QueryBase Insert(params object[] values)
        {
            InsertQuery query = new InsertQuery(values);
            query.Processor = mProcessor;

            AppendQueryToTransaction(query);

            return this;
        }

        /// <summary>
        /// Insert a list of objects to database
        /// </summary>
        public QueryBase Insert(IList values)
        {
            InsertQuery query = new InsertQuery(values);
            query.Processor = mProcessor;

            AppendQueryToTransaction(query);

            return this;
        }
        #endregion

        #region Select
        /// <summary>
        /// Select object(s)
        /// </summary>
        public SelectQuery Select
        {
            get
            {
                SelectQuery query = new SelectQuery();
                query.Processor = mProcessor;

                AppendQueryToTransaction(query);

                return query;
            }
        }
        #endregion

        #region Update
        /// <summary>
        /// Update object(s) to database
        /// </summary>
        public UpdateQuery Update(params object[] values)
        {
            UpdateQuery query = new UpdateQuery(values);
            query.Processor = mProcessor;

            AppendQueryToTransaction(query);

            return query;
        }

        /// <summary>
        /// Update a list of objects to database
        /// </summary>
        public UpdateQuery Update(IList values)
        {
            UpdateQuery query = new UpdateQuery(values);
            query.Processor = mProcessor;

            AppendQueryToTransaction(query);

            return query;
        }
        #endregion

        #region Delete
        /// <summary>
        /// Delete object(s) from database
        /// </summary>
        public QueryBase Delete(params object[] values)
        {
            DeleteQuery query = new DeleteQuery(values);
            query.Processor = mProcessor;

            AppendQueryToTransaction(query);

            return this;
        }

        /// <summary>
        /// Delete a list of objects from database
        /// </summary>
        public QueryBase Delete(IList values)
        {
            DeleteQuery query = new DeleteQuery(values);
            query.Processor = mProcessor;

            AppendQueryToTransaction(query);

            return this;
        }
        #endregion

        #region Transaction
        #region Begin
        /// <summary>
        /// Create a new transaction scope nested within the current transaction scope
        /// </summary>
        public virtual TransactionQuery Begin
        {
            get
            {
                if (mParentTransaction == null) InvalidQueryException.Publish(DataExceptionConstants.NoParentTransaction);

                TransactionQuery result = new TransactionQuery();
                result.Processor = mProcessor;
                result.ParentTransaction = mParentTransaction;
                AppendQueryToParent(result);
                result.mParentQuery = this;

                return result;
            }
        }
        #endregion

        #region End
        /// <summary>
        /// Finish transaction scope.
        /// </summary>
        /// <returns>The parent query who owns this child transaction scope</returns>
        public virtual QueryBase End
        {
            get
            {
                QueryBase result = null;
                if (mParentQuery == null) result = this;
                else result = mParentQuery;
                return result;
            }
        }
        #endregion
        #endregion

        #region Execute
        ExecuteResult resultSet = null;
        /// <summary>
        /// Execute the query and return result
        /// </summary>
        public ExecuteResult Execute()
        {
            if (mProcessor != null) resultSet = mProcessor.Execute(this);
            return resultSet;
        }
        #endregion

        #region Context
        private object mContext;
        /// <summary>
        /// Gets/Sets the special tag property. There is exactly one context object per transaction
        /// </summary>
        public object Context
        {
            get
            {
                object result = null;

                if (mParentQuery != null) result = mParentQuery.Context;
                else if (mParentTransaction != null) result = mParentTransaction.Context;
                else result = mContext;
                
                return result;
            }
            set
            {
                if (mParentQuery != null) mParentQuery.Context = value;
                else if (mParentTransaction != null) mParentTransaction.Context = value;
                else mContext = value;
            }
        }
        #endregion


        #region Given
        /// <summary>
        /// Assign value to Context property
        /// </summary>
        /// <param name="context">Can be any custom value</param>
        public QueryBase Given(object context)
        {
            this.Context = context;
            return this;
        }
        #endregion

        #region Constructors
        /// <summary>
        /// Default constructor
        /// </summary>
        public QueryBase()
        { }
        #endregion
    }
}
